package cn.tedu.luban.demand.main.service;

import cn.tedu.luban.demand.main.repository.DemandRepository;
import cn.tedu.luban.demand.protocol.bo.RequestOrderBO;
import cn.tedu.luban.demand.protocol.param.GrabOrderParam;
import cn.tedu.luban.demand.protocol.query.RequestOrderQuery;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.tedu.inn.protocol.ListRecordTotalBO;
import com.tedu.inn.protocol.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class DemandOrderService {

    @Autowired
    private DemandRepository demandRepository;

    public ListRecordTotalBO<RequestOrderBO> searchRequestOrders(RequestOrderQuery requestOrderQuery) throws BusinessException {
        //使用query先查询total条数
        Long total = demandRepository.getRequestOrderCount(requestOrderQuery);
        //判断total ==0
        ListRecordTotalBO<RequestOrderBO> bo=null;
        if (total==0) {
            bo=new ListRecordTotalBO<>(null,total);
        }else {
            //查询list分页数据
            List<RequestOrderBO> requestOrderBOS = demandRepository.queryRequestOrders(requestOrderQuery);
            //orderAmount=1000,profitScale=20     viewOrderAmount=1000*(100-20)/100
            calculateViewAmount(requestOrderBOS);
            bo=new ListRecordTotalBO<>(requestOrderBOS,total);
        }
        return bo;
    }

    private void calculateViewAmount(List<RequestOrderBO> requestOrderBOS) throws BusinessException {
        // viewOrderAmount=1000*(100-20)/100
        if (CollectionUtils.isNotEmpty(requestOrderBOS)) {
            BigDecimal profitScale = new BigDecimal(20);

            for (RequestOrderBO requestOrderBO : requestOrderBOS) {
                requestOrderBO.setProfitScale(profitScale);
                //计算师傅分润比例  100-20  80/100    0.8
                BigDecimal workerPercent =
                        new BigDecimal(100).subtract(profitScale).divide(new BigDecimal(100));

                //原始金额*师傅的分润比例
                BigDecimal viewAmount = new BigDecimal(requestOrderBO.getOrderAmount()).multiply(workerPercent);
                requestOrderBO.setViewOrderAmount(viewAmount.longValue());
            }
        }else {
            throw new BusinessException("9001","封装金额的需求单为空");
        }
    }

    public Boolean grabOrder(String requestOrderNo) {
        GrabOrderParam param = new GrabOrderParam();
        param.setRequestOrderNO(requestOrderNo);
        Integer result = demandRepository.grabOrder(param);
        return result==1;
    }

    public Boolean returnOrder(String requestOrderNo) {
        GrabOrderParam param = new GrabOrderParam();
        param.setRequestOrderNO(requestOrderNo);
        return demandRepository.returnOrder(param)==1;
    }
}
